//
//  GTVideoPlayer.m
//  WKWebViewStudy
//
//  Created by Jason Len on 2019/9/28.
//  Copyright © 2019年 Jason. All rights reserved.
//

#import "GTVideoPlayer.h"
#import <AVFoundation/AVFoundation.h>



@interface GTVideoPlayer()
    @property(nonatomic,strong,readwrite) AVAsset *asset;
    @property(nonatomic,strong,readwrite) AVPlayerItem *videoItem ;
    @property(nonatomic,strong,readwrite) AVPlayer *avPlayer;
    @property(nonatomic,strong,readwrite) AVPlayerLayer *playerLayer ;
@end

@implementation GTVideoPlayer

//单例模式的player实现
+(GTVideoPlayer *) Player{
    static GTVideoPlayer *player;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{ //单例
        player = [[GTVideoPlayer alloc]init];
    });
    return player;
}

-(void)playVideoWithUrl:(NSString *)videoUrl attachView:(UIView *)attachView{
    
    [self _stopPlay]; //播放之前先释放上次视频资源
    
    NSURL *videoURL = [NSURL URLWithString:videoUrl];
    
    _asset = [AVAsset assetWithURL:videoURL];
    
    _videoItem = [AVPlayerItem playerItemWithAsset:_asset];
    //监听视频状态变化
    [_videoItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    [_videoItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
    
    CMTime duration = _videoItem.duration;
    CGFloat videoDuration = CMTimeGetSeconds(duration);
    
    _avPlayer = [AVPlayer playerWithPlayerItem:_videoItem];
    
    //监听播放完成。（利用NotificationCenter单例模式监听）
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_handlePlayEnd) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    //监听播放进度
    [_avPlayer addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        NSLog(@"播放进度：%@",@(CMTimeGetSeconds(time)));
    }];
    
    _playerLayer = [AVPlayerLayer playerLayerWithPlayer:_avPlayer];
    
    _playerLayer.frame = attachView.bounds;
    
    //将视频layer添加到 attachView
    [attachView.layer addSublayer: _playerLayer];
}

-(void)_stopPlay{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [_videoItem removeObserver:self forKeyPath:@"status"];
    [_videoItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
    [_playerLayer removeFromSuperlayer];
    _videoItem = nil;
    _avPlayer = nil;
}


-(void)_handlePlayEnd{
    NSLog(@"");
    
    [_avPlayer seekToTime:CMTimeMake(1, 1)];
}

//实现播放状态监听
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    NSLog(@"change");
    if([keyPath isEqualToString:@"status"]){
        if(((NSNumber *)[change objectForKey:NSKeyValueChangeNewKey]).integerValue == AVPlayerItemStatusReadyToPlay){
            NSLog(@"before play");
            [_avPlayer play];
        }
    }else if([keyPath isEqualToString:@"loadedTimeRanges"]){
        NSLog(@"缓冲 %@", [change objectForKey:NSKeyValueChangeNewKey]);
    }
}


@end
